package com.aaa.service.Impl;

import cn.hutool.core.date.DateUtil;
import com.aaa.entity.Role;
import com.aaa.entity.RoleMenu;
import com.aaa.mapper.RoleMapper;
import com.aaa.mapper.RoleMenuMapper;
import com.aaa.service.RoleService;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private RoleMapper roleMapper;

    public List<Role> listAll(String keyword) {
        List<Role> RoleList = roleMapper.listPage(keyword);
        RoleList.forEach((item) -> {
            item.setMenus(roleMapper.listRoles(Math.toIntExact(item.getRid())));
        });
        return RoleList;
    }


    @Override
    public DefaultMsg addOrUpdate(Role role, String menuIds) {
        role.setCreateDate(DateUtil.now());
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer result;
        if (role.getRid() == null) {
            result = baseMapper.insert(role);
        } else {
            result = baseMapper.updateById(role);
//            删除原先的角色
            roleMenuMapper.delete(new QueryWrapper<RoleMenu>().eq("r_id", role.getRid()));
        }
//        拆分menuIds
        String[] mids = menuIds.split(",");
        for (String mid : mids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRId(role.getRid());
            roleMenu.setMId(Long.valueOf(mid));
            roleMenuMapper.insert(roleMenu);
        }
        if (result != null || result != 0) {
            return defaultMsg;
        } else {
            defaultMsg.setMsg("添加或修改失败");
            return defaultMsg;
        }
    }

    @Override
    public DefaultMsg delete(Integer rid) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer delete = baseMapper.deleteById(rid);
        Integer r_id = roleMenuMapper.delete(new QueryWrapper<RoleMenu>().eq("r_id", rid));
        if (delete == 0 || delete == null || r_id == 0 || r_id == null) {
            defaultMsg.setSuccess(0);
            defaultMsg.setMsg("删除失败");
        }
        return defaultMsg;
    }
}

